<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel">
        <template slot="menuLeft">
          <el-button v-if="permissions.pfoc_filelibrary_add"  type="primary" icon="el-icon-plus" @click="uploadFile">上传</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text"  size="small" plain  @click="$refs.crud.rowEdit(scope.row,scope.index)">重命名</el-button>
          <el-button type="text"  size="small" plain  @click="previewFile(scope.row,scope.index)">预览</el-button>
          <el-button type="text"  size="small" plain  @click="downloadFile(scope.row)">下载</el-button>
          <el-button type="text"  size="small" plain  @click="handleDel(scope.row,scope.index)">删除</el-button>
        </template>
      </avue-crud>
      <el-dialog title=""
                 :visible.sync="dialogVisible"
                 width="50%"
                 lock-scroll
                 v-if="dialogVisible"
                 :fullscreen="dialogFull">

        <template slot="title">
          <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
                <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                上传
            </span>
            <div class="avue-crud__dialog__menu" style="margin-top: -7px;margin-right: 10px;" @click="dialogFull? dialogFull=false: dialogFull=true">
              <i class="el-icon-full-screen"></i>
            </div>
          </div>
        </template>
        <uploadFile ref="uploadRef" @closeUpload="closeUpload"/>
      </el-dialog>

      <el-dialog :visible.sync="previewDialogVisible" title="文件预览" :fullscreen="true">
          <div v-if="isImagePreview" class="full-screen-container">
            <img :src="previewUrl" alt="preview" class="full-screen-image">
          </div>
          <div v-else>
            <iframe :src="previewUrl" style="width: 100%; height: 80vh;"></iframe>
          </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, addObj, putObj, delObj ,downloadFileByPath} from '@/api/pfoc/filelibrary'
import { tableOption } from '@/const/crud/pfoc/filelibrary'
import { mapGetters } from 'vuex'
import uploadFile from "@/views/pfoc/filelibrary/file_upload.vue";
import { Base64 } from 'js-base64';

export default {
  name: 'fileUpload',
  components: {uploadFile},
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      dialogVisible: false,
      dialogFull: false,
      previewDialogVisible: false,
      previewUrl: '',
      isImagePreview: false

    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.pfoc_filelibrary_add, false),
        delBtn: this.vaildData(this.permissions.pfoc_filelibrary_del, false),
        editBtn: this.vaildData(this.permissions.pfoc_filelibrary_edit, false)
      }
    }
  },
  methods: {
    // 列表查询
    getList(page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除文件：' + row.fileName , '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/pfoc/filelibrary/export', this.searchForm, 'filelibrary.xlsx')
    },
    uploadFile(){
      this.dialogVisible = true;
    },
    closeUpload(){
      this.dialogVisible = false;
      this.getList(this.page)
    },
    downloadFile(row) {
      const fileName = row.fileName; // 原文件名
      const path = row.locationInfo; // 文件路径+文件名

      downloadFileByPath(path).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName); // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
      }).catch(error => {
        this.$notify.error('下载失败');
        console.error('下载失败:', error);
      });
    },
    previewFile(row,index) {
    /*  const path = row.fictitiousPath;
      this.isImagePreview = this.isImage(path);
      if (this.isImagePreview) {
        this.previewUrl = path;
      } else {
        //获取当前host
        const path =window.location.origin+row.fictitiousPath; // 文件路径+文件名
        this.previewUrl = 'http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(path));
        window.open(this.previewUrl, '_blank');
    }*/
      const path =window.location.origin+row.fictitiousPath; // 文件路径+文件名
      this.previewUrl =  window.location.origin+'/preview/onlinePreview?url='+encodeURIComponent(Base64.encode(path));
      window.open(this.previewUrl, '_blank');
      // this.previewDialogVisible = true;
    },
    isImage(path) {
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'];
      const ext = path.split('.').pop().toLowerCase();
      return imageExtensions.includes(ext);
    }
  }
}
</script>
<style scoped>
.full-screen-container {
  width: 100%;
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000; /* 背景色设为黑色，可根据需求调整 */
}

.full-screen-image {
  max-width: 90%; /* 最大宽度可以根据需求调整，避免紧贴屏幕边缘 */
  max-height: 90%; /* 最大高度可以根据需求调整，避免紧贴屏幕边缘 */
  object-fit: contain; /* 保持图片的宽高比，且被包含在容器内 */
}
</style>
